package com.itfreer.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;

import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.gzgzjjr.dao.GzgzjjrDao;
import com.itfreer.gzgzjjr.entity.GzgzjjrEntity;
import com.itfreer.utils.json.JsonUtils;
import com.itfreer.vkqtj.dao.VkqtjDao;
import com.itfreer.vkqtj.entity.VkqtjEntity;
import com.itfreer.workdate.CalculateServerImp;
import com.itfreer.workdate.DayInfo;

//获取考勤统计
@Component
@Path("/attendance")
public class GetAttendance {
	@Autowired
	VkqtjDao vkqtjdao;
	@Autowired
	GzgzjjrDao gzjjrdao;
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@POST
	@Path("/result")
	public List attendance(@Context HttpServletRequest request,String data) {
		HashMap<String, Object> args = getRestParam(data);
		String userid = null;
		Date kssj = null;
		Date jssj = null;
		String dptid = null;
		List list=new ArrayList();
		Map map=new HashedMap();
		CalculateServerImp ch = new CalculateServerImp();
		try {
			//获取参数
			if(args!=null) {
				if (args.containsKey("userid") && args.get("userid") != null) {
					userid = args.get("userid").toString();
				}
				if (args.containsKey("kssj") && args.get("kssj") != null) {
					kssj=strToDate(args.get("kssj").toString()+" 00:00:00",2);
				}
				if (args.containsKey("jssj") && args.get("jssj") != null) {
					jssj =strToDate(args.get("jssj").toString()+" 23:59:59",2);
				}
				if (args.containsKey("dptid") && args.get("dptid") != null) {
					dptid =args.get("dptid").toString();
				}
			}
			Map<String,Object> where =new HashedMap();
			if(dptid!=null) {
				where.put("dptid:=", dptid);
				userid=null;
			}else {
				where.put("userid:=", userid);
			}
			where.put("sj:>=", kssj);
			where.put("sj:<=", jssj);
			Map<String,Integer> order =new HashedMap();//根据人员排序
			order.put("userid", 1);
			
			List<VkqtjEntity> vkqtjEntitys=vkqtjdao.getEntitys(null, where, order, 1000, 1);
			
			//获取特殊工作日和节假日
			Map<String,Object> datewhere =new HashedMap();
			datewhere.put("spedate:>=", kssj);
			datewhere.put("spedate:<=", jssj);
			List<GzgzjjrEntity> gzjjrEntitys=gzjjrdao.getEntitys(null, datewhere, null, 1000, 1);
			for(GzgzjjrEntity gzjjrEntity: gzjjrEntitys) {
				if("1".equals(gzjjrEntity.getType())) {
					ch.holiday.add(dateToStr(gzjjrEntity.getSpedate(),1));
				}else {
					ch.speworkday.add(dateToStr(gzjjrEntity.getSpedate(),1));
				}
			}
			
			List<String> jobDates=ch.workDays(dateToStr(kssj,1), dateToStr(jssj,1));
			double cqts=0,qjts=0,ccts=0,kgts=0,cdcs=0,cdsc=0,ztcs=0,ztsc=0,sbqkcs=0,xbqkcs=0;
			if(vkqtjEntitys.size()==0) {
				return null;
			}
			//出勤天数,请假天数,出差天数,旷工天数,迟到次数,迟到时长,早退次数,早退时长,上班缺卡次数,下班缺卡次数
			for(int i=0;i<vkqtjEntitys.size();i++) {
				VkqtjEntity entity = vkqtjEntitys.get(i);
				if(userid==null) {
					userid=entity.getUserid();
				}
				if(!userid.equals(entity.getUserid())) {//根据用户不同分别处理
					userid=entity.getUserid();
					map.put("gzts", jobDates.size());//工作天数
					map.put("username", vkqtjEntitys.get(i-1).getUsername());
					map.put("dptname", vkqtjEntitys.get(i-1).getDptname());
					map.put("cqts", cqts);
					map.put("qjts", qjts);
					map.put("ccts", ccts);
					kgts=jobDates.size()-cqts-qjts;
					map.put("kgts", kgts);
					map.put("cdcs", cdcs);
					map.put("cdsc", cdsc);
					map.put("ztcs", ztcs);
					map.put("ztsc", ztsc);
					map.put("sbqkcs", sbqkcs);
					map.put("xbqkcs", xbqkcs);
					//记录存储至list,清零
					list.add(map);
					cqts=qjts=ccts=kgts=cdcs=cdsc=ztcs=ztsc=sbqkcs=xbqkcs=0;
					map=new HashedMap();
				}
				Map<String, DayInfo> result = new HashMap<>();
				for(String jobDate:jobDates) {
					if(jobDate.equals(dateToStr(entity.getSj(),1))) {//如果当天存在记录
						if("签到".equals(entity.getType())) {//签到记录
							if(entity.getKssj()==null) {//上班未打卡+1
								entity.setKssj(getNormalTime(entity.getJssj(),1));
								sbqkcs+=1;
							}else if(entity.getJssj()==null) {//下班未打卡+1
								entity.setJssj(getNormalTime(entity.getKssj(),2));
								xbqkcs+=1;
							}
							ch.workTimes(dateToStr(entity.getKssj(),2), dateToStr(entity.getJssj(),2), result);
							DayInfo dayInfo=result.get(dateToStr(entity.getKssj(),1));//获取当天的信息
							cqts+=1;//出勤天数+1
							if(dayInfo.getMorning().getLateTime()>0) {//迟到时间大于0时
								cdcs+=1;//迟到次数+1
								cdsc+=dayInfo.getMorning().getLateTime();//迟到时长增加
							}
							if(dayInfo.getAfternoon().getLeaveEarlyTime()>0) {//早退时间大于0时
								ztcs+=1;//早退次数+1
								ztsc+=dayInfo.getAfternoon().getLeaveEarlyTime();//早退时长增加
							}
						}else if("出差".equals(entity.getType())) {
							if(entity.getKssj()!=null && entity.getJssj()!=null) {
								float count=ch.workDays(dateToStr(entity.getKssj(),2), dateToStr(entity.getJssj(),2), result, "出差");
								ccts+=count;//出差天数增加
								cqts+=count;//出勤天数增加
							}
						}else if("请假".equals(entity.getType())) {
							if(entity.getKssj()!=null && entity.getJssj()!=null) {
								float count=ch.workDays(dateToStr(entity.getKssj(),2), dateToStr(entity.getJssj(),2), result, "请假");
								qjts+=count;//请假天数增加
							}
						}
						break;
					}
				}
			}
			//最后一位用户
			map.put("gzts", jobDates.size());//工作天数
			map.put("username", vkqtjEntitys.get(vkqtjEntitys.size()-1).getUsername());
			map.put("dptname", vkqtjEntitys.get(vkqtjEntitys.size()-1).getDptname());
			map.put("cqts", cqts);
			map.put("qjts", qjts);
			map.put("ccts", ccts);
			kgts=jobDates.size()-cqts-qjts;
			map.put("kgts", kgts);
			map.put("cdcs", cdcs);
			map.put("cdsc", cdsc);
			map.put("ztcs", ztcs);
			map.put("ztsc", ztsc);
			map.put("sbqkcs", sbqkcs);
			map.put("xbqkcs", xbqkcs);
			list.add(map);
			return list;
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
		}
		
		return null;
	}
	
	//获取正常上下班时间//时间固定
	public static Date getNormalTime(Date today,int type) {
		Date date = null;
		if(type==1) {//上班
			String day=dateToStr(today,1);
			day=day+" 9:00:00";
			date=strToDate(day,2);
		}else if(type==2) {//下班
			String day=dateToStr(today,1);
			day=day+" 18:00:00";
			date=strToDate(day,2);
		}
		return date;
	}
	
	public static String dateToStr(Date date,int type) {
		String str = "";
		if(type==1) {
			str=new SimpleDateFormat("yyyy-MM-dd").format(date);
		}else if(type==2) {
			str=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
		}
		return str;
	}
	public static Date strToDate(String str,int type) {
		Date date= null;
		try {
			if(type==1) {
				date=new SimpleDateFormat("yyyy-MM-dd").parse(str);
			}else if(type==2) {
				date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str);
			}
			return date;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 解决请求参数问题
	 * 
	 * @param data
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static HashMap<String, Object> getRestParam(String data) {
		HashMap<String, Object> args = null;
		if (data == null || "".equals(data.trim()))
			return args;
		// 解决不同浏览器返回传递参数不一致问题-s-
		try {
			args = JsonUtils.toBean(data, HashMap.class);

		} catch (Exception e) {
			try {
				String ENCODE = "UTF-8";
				data = java.net.URLDecoder.decode(data, ENCODE);
				if (data != null && !"".equals(data.trim())) {
					String[] lst = data.split("&");
					args = new HashMap<String, Object>();
					for (String item : lst) {
						if (item == null || "".equals(item.trim()))
							continue;
						String[] ivalue = item.split("=");
						if (ivalue != null) {
							if (ivalue.length > 1) {
								args.put(ivalue[0], ivalue[1]);
							} else {
								args.put(ivalue[0], null);
							}
						}

					}
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		// 解决不同浏览器返回传递参数不一致问题-e-
		return args;
	}
	
}
